package com.zyao89.view.zloading.rect;

import com.zyao89.view.zloading.base.BaseStateBuilder;
import com.zyao89.view.zloading.util.NumCalcUtil;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;

/**
 * Created by zyao89 on 2018/3/17.
 * Contact me at 305161066@qq.com or zyao89@gmail.com
 * For more projects: https://github.com/zyao89
 * My Blog: https://zyao89.cn
 */
public class StairsRectBuilder extends BaseStateBuilder {
    /**
     * 台阶总数
     */
    private final int FLOOR_NUM = 5;
    /**
     * 动画间隔时长
     */
    private volatile long mAnimateDurationTime = 500;
    /**
     * 当前台阶数
     */
    private volatile int mCurrFloorNum = 0;
    private volatile float mCurrAnimatedValue = 0;
    private Paint mPaint;
    private float mR;
    private RectFloat mStairRectF;

    @Override
    protected int getStateCount() {
        return FLOOR_NUM;
    }

    @Override
    protected void initParams(Context context, Paint paint) {
        mPaint = paint;
        mPaint.setStyle(Paint.Style.FILLANDSTROKE_STYLE);
        mR = getAllSize();
        mStairRectF = new RectFloat();
    }

    @Override
    protected void onComputeUpdateValue(AnimatorValue animation, float animatedValue, int state) {
        mCurrFloorNum = state;
        mCurrAnimatedValue = animatedValue;
    }

    @Override
    protected void onDraw(Canvas canvas) {

        // 台阶高度
        float floorHeight = mR * 2 / FLOOR_NUM;
        float space = floorHeight * 0.5f;

        // 起点
        float startXP = NumCalcUtil.subtract(getViewCenterX(), mR);
        float startYP = NumCalcUtil.add(getViewCenterY(), mR);

        // 清
        mStairRectF.clear();
        for (int i = 0; i < FLOOR_NUM; i++) {
            if (i > mCurrFloorNum) { // 限制层
                break;
            }
            if (i == mCurrFloorNum) { // 当前台阶
                mStairRectF.modify(startXP, NumCalcUtil.add(NumCalcUtil.subtract(startYP, (i + 1) * floorHeight), space), NumCalcUtil.add(startXP, (i + 1) * floorHeight) * mCurrAnimatedValue, NumCalcUtil.subtract(startYP, i * floorHeight));
            } else { // 非当前台阶
                mStairRectF.modify(startXP, NumCalcUtil.add(NumCalcUtil.subtract(startYP, (i + 1) * floorHeight), space), NumCalcUtil.add(startXP, (i + 1) * floorHeight), NumCalcUtil.subtract(startYP, i * floorHeight));
            }
            canvas.drawRect(mStairRectF, mPaint);
        }
    }

    @Override
    protected void prepareStart(AnimatorValue animation) {
        mAnimateDurationTime = ceil(getAnimationDuration() * 0.5);

        // 动画间隔
        animation.setDuration(mAnimateDurationTime);
        animation.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);
    }

    @Override
    protected void prepareEnd() {
        mCurrFloorNum = 0;
        mCurrAnimatedValue = 0;
    }
}
